<template>
  <div class="superviseTask">
    <!-- 导航栏 -->
    <div class="header_body">
      <header-nav
        :leftArrow="true"
        :titelText="id == '' ? '新建任务' : '编辑任务'"
        :slefBack="true"
        @goBack="goBack"
      ></header-nav>
    </div>

    <div class="task">
      <van-form @submit="onSubmit">
        <van-field
          v-model="taskForm.checkTypeName"
          is-link
          readonly
          required
          label="检查类型"
          placeholder="请选择"
          @click="checkTypeSelect"
        />
        <van-field
          v-model="taskForm.checkerName"
          readonly
          required
          label="主办人"
        />
        <van-field
          v-model="taskForm.organizerName"
          is-link
          readonly
          required
          placeholder="请选择"
          label="协办人"
          @click="organizerSelect"
        />
        <div class="line10"></div>
        <van-field
          v-model="taskForm.openPlaceInfo.locationTypeName"
          is-link
          readonly
          required
          label="场所类型"
          placeholder="请选择"
          @click="idTypeSelect"
        />
        <van-field
          v-model="taskForm.openPlaceInfo.placeName"
          required
          maxlength="16"
          show-word-limit
          label="场所名称"
          placeholder="请输入"
        />
        <van-field
          style="padding-left: 24px !important"
          v-model="areaValue"
          is-link
          readonly
          label="场所地址"
          placeholder="请选择所在地区"
          @click="areaShow = true"
        />
        <van-field
          style="padding-left: 24px !important"
          v-model="taskForm.openPlaceInfo.address"
          type="textarea"
          rows="1"
          autosize
          maxlength="32"
          show-word-limit
          label="详细地址"
          placeholder="请输入"
        />
        <div class="submitBtn">
          <van-button
            plain
            block
            type="primary"
            class="btn-left"
            native-type="submit"
            style="margin-right: 8px"
          >
            保存
          </van-button>
          <van-button block type="primary" class="btn-right" @click="goCheck()">
            开始检查
          </van-button>
        </div>
      </van-form>

      <!-- 类型，方式选择 -->
      <van-popup v-model:show="picker" round position="bottom">
        <van-picker
          :columns="pickerData"
          @cancel="picker = false"
          @confirm="pickerConfirm"
        />
      </van-popup>

      <!-- 协办人 -->
      <van-popup v-model:show="organizerPicker" round position="bottom">
        <van-picker
          :columns="organizerData"
          @cancel="organizerPicker = false"
          @confirm="organizerConfirm"
        />
      </van-popup>

      <!-- 住址，注册地区选择 -->
      <van-popup v-model:show="areaShow" round position="bottom">
        <van-cascader
          v-model="cascaderValue"
          title="请选择所在地区"
          :options="aeraData"
          :field-names="{
            text: 'name',
            value: 'code',
            children: 'children',
          }"
          @close="areaShow = false"
          @finish="onFinish"
        />
      </van-popup>
    </div>
  </div>
</template>
<script setup>
import {
  showNotify,
  showSuccessToast,
  showConfirmDialog,
  showFailToast,
} from 'vant'
import aeraData from '../../util/pcas-code.json'
const { usePublic, useTasks } = $globalStore
const router = useRouter()
const route = useRoute()
const id = ref(route.query.id)

const goBack = () => {
  showConfirmDialog({
    title: '提示',
    message: '退出后已填内容无法保存，确定退出吗？',
  })
    .then(() => {
      router.go(-1)
    })
    .catch(() => {
      // on cancel
    })
}

//表单
const taskForm = ref({
  checkTypeId: '',
  checkTypeName: '',
  openPlaceInfo: {
    locationTypeId: '', //场所类型id
    locationTypeName: '', //场所类型名称
    placeName: '', //场所名称
    address: '', //详细场所地址
    countyCode: 0, //住址，注册区码
    county: '', //住址，注册区名
    townCode: 0, //住址，注册街镇码
    town: '', //住址，注册街镇名
  },
  checkerId: JSON.parse(sessionStorage.getItem('userInfo')).id,
  checkerName: JSON.parse(sessionStorage.getItem('userInfo')).userName, //主办人
  organizerId: '', //协办人id
  organizerName: '', //协办人姓名
})

//选项数据
const picker = ref(false)
const pickerData = ref([])
const pickerType = ref('')
const getCheckTypeData = async (val) => {
  const res = await usePublic.getDictionary(val)
  if (res.code == 0) {
    pickerData.value = []
    res.data.forEach((element) => {
      let obj = {
        text: element.configName,
        value: element.id,
      }
      pickerData.value.push(obj)
    })
  }
}
const pickerConfirm = (val) => {
  console.log(val)
  if (pickerType.value == 'check_type') {
    taskForm.value.checkTypeId = val.selectedOptions[0].value
    taskForm.value.checkTypeName = val.selectedOptions[0].text
  } else if (pickerType.value == 'check_mode') {
    taskForm.value.checkModeId = val.selectedOptions[0].value
    taskForm.value.checkModeName = val.selectedOptions[0].text
  } else if (pickerType.value == 'place_type') {
    taskForm.value.openPlaceInfo.locationTypeId = val.selectedOptions[0].value
    taskForm.value.openPlaceInfo.locationTypeName = val.selectedOptions[0].text
  }
  picker.value = false
}

//检查类型
const checkTypeSelect = () => {
  pickerType.value = 'check_type'
  getCheckTypeData('check_type')
  picker.value = true
}

//协办人选择
const organizerPicker = ref(false)
const organizerData = ref([])
//打开协办人选择
const organizerSelect = () => {
  getOrganizers()
  organizerPicker.value = true
}
//选择协办人
const organizerConfirm = (val) => {
  taskForm.value.organizerId = val.selectedOptions[0].value
  taskForm.value.organizerName = val.selectedOptions[0].text
  organizerPicker.value = false
}
//获取协办人数据源
const getOrganizers = async () => {
  const res = await usePublic.getOrganizer()
  if (res.code == 0) {
    organizerData.value = []
    res.data.forEach((element) => {
      let obj = {
        text: element.userName,
        value: element.id,
      }
      organizerData.value.push(obj)
    })
  }
}

//场所类型
const idTypeSelect = () => {
  pickerType.value = 'place_type'
  getCheckTypeData('place_type')
  picker.value = true
}

//地区选择
const areaShow = ref(false)
const areaValue = ref('')
const cascaderValue = ref('')

const onFinish = (val) => {
  let arr = []
  val.selectedOptions.forEach((item) => {
    arr.push(item.name)
  })
  taskForm.value.openPlaceInfo.countyCode = val.selectedOptions[1].code
  taskForm.value.openPlaceInfo.county = val.selectedOptions[1].name
  taskForm.value.openPlaceInfo.townCode = val.selectedOptions[2].code
  taskForm.value.openPlaceInfo.town = val.selectedOptions[2].name
  areaValue.value = arr.join('')
  areaShow.value = false
}

//保存任务信息
const backFlag = ref(false)

const onSubmit = async () => {
  console.log(taskForm.value, '11111')
  if (taskForm.value.checkTypeId == '') {
    return showNotify({ type: 'danger', message: '请选择检查类型' })
  } else if (taskForm.value.organizerName == '') {
    return showNotify({ type: 'danger', message: '请选择协办人' })
  } else if (taskForm.value.openPlaceInfo.locationTypeId == '') {
    return showNotify({ type: 'danger', message: '请选择场所类型' })
  } else if (taskForm.value.openPlaceInfo.placeName == '') {
    return showNotify({ type: 'danger', message: '请输入场所名称' })
  } else if (taskForm.value.openPlaceInfo.TownCode == 0) {
    return showNotify({ type: 'danger', message: '请选择场所地址' })
  } else if (taskForm.value.openPlaceInfo.address == '') {
    return showNotify({
      type: 'danger',
      message: '请输入场所详细地址',
    })
  }

  if (id.value == '') {
    const res = await useTasks.saveTasks(taskForm.value)
    if (res.code == 0) {
      showSuccessToast('保存成功')
      if (backFlag.value) {
        const s = await useTasks.startTasks(res.data)
        if (s.code == 0) {
          router.push({
            name: 'tasksCheck',
            query: { id: res.data, from: 1 },
          })
        }
      } else {
        router.go(-1)
      }
    } else {
      showFailToast(res.message)
    }
  } else {
    Reflect.set(taskForm.value, 'id', id.value)
    const res = await useTasks.updateTasks(taskForm.value)
    if (res.code == 0) {
      showSuccessToast('修改成功')
      if (backFlag.value) {
        const s = await useTasks.startTasks(id.value)
        if (s.code == 0) {
          router.push({
            name: 'tasksCheck',
            query: { id: id.value },
          })
        }
      } else {
        router.go(-1)
      }
    } else {
      showFailToast(res.message)
    }
  }
}
//开始检查
const goCheck = () => {
  backFlag.value = true
  onSubmit()
}

onMounted(async () => {
  if (id.value != '') {
    const res = await useTasks.taskInfo(id.value)
    if (res.code == 0) {
      taskForm.value.checkTypeName = res.data.checkTypeName
      taskForm.value.checkTypeId = res.data.checkTypeId
      taskForm.value.organizerName = res.data.organizerName
      taskForm.value.organizerId = res.data.organizerId
      taskForm.value.openPlaceInfo.locationTypeId =
        res.data.openPlaceInfo.locationTypeId
      taskForm.value.openPlaceInfo.locationTypeName =
        res.data.openPlaceInfo.locationTypeName
      taskForm.value.openPlaceInfo.placeName = res.data.openPlaceInfo.placeName

      //注册地址，住址
      taskForm.value.openPlaceInfo.countyCode =
        res.data.openPlaceInfo.countyCode
      taskForm.value.openPlaceInfo.county = res.data.openPlaceInfo.county
      taskForm.value.openPlaceInfo.townCode = res.data.openPlaceInfo.townCode
      taskForm.value.openPlaceInfo.town = res.data.openPlaceInfo.town
      cascaderValue.value = res.data.openPlaceInfo.townCode
      areaValue.value =
        '长沙市' + res.data.openPlaceInfo.county + res.data.openPlaceInfo.town
      taskForm.value.openPlaceInfo.address = res.data.openPlaceInfo.address
    }
  }
})
</script>
<style lang="scss" scoped>
.superviseTask {
  width: 100%;
  height: calc(100%);
  overflow-y: hidden;
  background-color: #ffffff;
  .task {
    width: 100%;
    height: calc(100% - 122px);
    overflow-y: auto;
    margin-top: 46px;
  }
}

.line10 {
  width: 100%;
  height: 10px;
  background-color: #f7f7f7;
}

.partyType {
  padding: 16px;
  border-bottom: 1px solid #f5f5f5;
  .title {
    font-size: 16px;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 24px;
    color: #4d4d4d;
    margin-bottom: 14px;
  }

  .party {
    display: flex;
    align-items: center;
    padding: 0 8px;

    .partyItem1 {
      width: 9.8125rem;
      height: 2.25rem;
      line-height: 2.25rem;
      text-align: center;
      background-color: #f2f2f2;
      border: 1px solid #f2f2f2;
      border-radius: 4px;
      font-size: 14px;
      font-weight: 400;
      color: #666666;
      margin-right: 12px;
      flex-grow: 1;
    }

    .partyItem2 {
      width: 9.8125rem;
      height: 2.25rem;
      line-height: 2.25rem;
      background-color: #f2f2f2;
      border: 1px solid #f2f2f2;
      border-radius: 4px;
      font-size: 14px;
      font-weight: 400;
      color: #666666;
      text-align: center;
      flex-grow: 1;
    }

    .partyItem1Active {
      border: 1px solid #1764ce;
      background-color: rgba(23, 100, 206, 0.1);
      color: #1764ce;
    }
  }
}

.sex {
  padding: 16px;
  display: flex;
  border-bottom: 1px solid #f5f5f5;

  .title {
    width: 130px;
    font-size: 16px;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 24px;
    color: #4d4d4d;
  }
}

.area {
  padding: 16px 16px 0 16px;
  // display: flex;
  // border-bottom: 1px solid #f5f5f5;

  .title {
    width: 120px;
    font-size: 16px;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 24px;
    color: #4d4d4d;
  }
}
</style>
